package com.busionline.wotu.bannerview.view;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import com.busionline.wotu.bannerview.adapter.BannerAdapter;
import com.busionline.wotu.bannerview.listener.DefaultActivityLifecycleCallbacks;
import com.busionline.wotu.bannerview.listener.OnBannerItemClickListener;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义无限轮播
 * Created by admin on 2017/11/6.
 */

public class BannerViewPager extends ViewPager {
    private static final String TAG = "BannerViewPager";
    //滚动消息
    private static final int SCROLL_MSG = 0x0011;
    private final Activity mActivity;
    private BannerScroller mScroller;
    //轮播间隔
    private long mCutDownTime = 3500;
    private BannerAdapter mBannerAdapter;
    private Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SCROLL_MSG:
                    int currentIndex = getCurrentItem() + 1;
                    setCurrentItem(currentIndex);
                    startRoll();
                    break;
            }
        }
    };
    //条目点击事件
    private OnBannerItemClickListener mItemClickListener;
    private List<View> mConvertViews;
    private BannerPagerAdapter mBannerPagerAdapter;//viewPager adapter

    public OnBannerItemClickListener getBannerListener() {
        return mItemClickListener;
    }

    public void setBannerListener(OnBannerItemClickListener bannerListener) {
        this.mItemClickListener = bannerListener;
    }

    public BannerViewPager(Context context) {
        this(context, null);
    }

    public BannerViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
         mActivity = (Activity) context;
        //改变viewpager切换的速率
        try {
            Field field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);
            mScroller = new BannerScroller(context);
            field.set(this, mScroller);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        //复用集合初始化
        mConvertViews = new ArrayList<>();
    }


    public void setAdapter(BannerAdapter adapter) {
        mBannerAdapter = adapter;
         mBannerPagerAdapter = new BannerPagerAdapter();
        setAdapter(mBannerPagerAdapter);
        mActivity.getApplication().registerActivityLifecycleCallbacks(lifecycleCallback);
    }

    /**
     *  管理生命周期
     */
    private DefaultActivityLifecycleCallbacks lifecycleCallback = new DefaultActivityLifecycleCallbacks(){
        @Override
        public void onActivityStarted(Activity activity) {
            if(activity == mActivity){
                //开始轮播
                startRoll();
            }
        }

        @Override
        public void onActivityStopped(Activity activity) {
            if(activity == mActivity){
                //结束轮播
                mHandle.removeMessages(SCROLL_MSG);
            }
        }
    };



    /**
     * 开始轮播
     */
    public void startRoll() {
        mHandle.removeMessages(SCROLL_MSG);
        mHandle.sendEmptyMessageDelayed(SCROLL_MSG, mCutDownTime);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mActivity.getApplication().unregisterActivityLifecycleCallbacks(lifecycleCallback);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        /**
         * 坑，解决在RecyclerView中使用的bug
         * 设ViewPager中有3张照片
         * 当ViewPager滑动一遍之后，向下滑动RecyclerView列表
         * 直到完全隐藏此ViewPager，并执行了onDetachedFromWindow
         * 再回来时，将会出现bug，第一次滑动时没有动画效果，并且，经常出现view没有加载的情况
         */
        try {
            Field mFirstLayout = ViewPager.class.getDeclaredField("mFirstLayout");
            mFirstLayout.setAccessible(true);
            mFirstLayout.set(this, false);
            mBannerPagerAdapter.notifyDataSetChanged();
            setCurrentItem(getCurrentItem());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置滚动时间
     *
     * @param millisecond
     */
    public void setScrollDuration(int millisecond) {
        mScroller.setmDuration(millisecond);
    }

    /**
     * 拿到复用界面
     *
     * @return
     */
    public View getConvertView() {
        for (View convertView : mConvertViews) {
            if (convertView.getParent() == null) {
                return convertView;
            }
        }
        return null;
    }

    private class BannerPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            //这个view的id是不是这个object(谷歌这里把view当id使用)
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            final int realPosition = position % mBannerAdapter.getCount();
            View bannerView = mBannerAdapter.getView(realPosition, getConvertView());
            if (mItemClickListener != null) {
                bannerView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mItemClickListener.OnBannerClick(realPosition);
                    }
                });

            }
            container.addView(bannerView);
            return bannerView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            mConvertViews.add((View) object);
        }
    }
}
